package com.saikuo.service.dao.impl;

import com.saikuo.service.dao.IUserDao;
import com.saikuo.service.model.User;
import com.saikuo.service.vo.UserAddressView;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.List;

/**
 * Created by shanchangyu on 16/10/14.
 */
@Repository
public class UserDaoImpl extends JdbcDaoSupport implements IUserDao {
    private static final BeanPropertyRowMapper<User> mapper =
            new BeanPropertyRowMapper<>(User.class);
    private static final BeanPropertyRowMapper<UserAddressView> mapperAddress =
            new BeanPropertyRowMapper<>(UserAddressView.class);

    @Autowired
    UserDaoImpl(DataSource dataSource) {
        setDataSource(dataSource);
    }


    private static final String REGISTER_USER = "insert into y_user(mobile,password,create_time) values (?,?,now())";

    @Override
    public boolean register(String mobile, String password) {
        return 1 == this.getJdbcTemplate().update(REGISTER_USER, new Object[]{mobile, password});
    }

    private static final String UPDATE_PWD = "update y_user set password=? where " +
            "mobile=?";

    @Override
    public boolean updatePassword(String mobile, String newPassword) {
        return 1 == this.getJdbcTemplate().update(UPDATE_PWD,
                new Object[]{newPassword, mobile});
    }

    private static final String CHANGE_PWD_BY_UID = "update y_user set password=? where " +
            "id=?";

    @Override
    public boolean changePasswordByUid(int userId, String newPassword) {
        return 1 == this.getJdbcTemplate().update(CHANGE_PWD_BY_UID,
                new Object[]{newPassword, userId});
    }

    private static final String GET_PWD_BY_UID = "select password from y_user " +
            "where id=?";

    @Override
    public String getPasswordByUid(int userId) {
        return this.getJdbcTemplate().queryForList(
                GET_PWD_BY_UID, new Object[]{userId},
                String.class).get(0);
    }

    private static final String GET_USER_BY_MOBILE = "select * from y_user where mobile=?";

    @Override
    public User getUserByMobile(String mobile) {
        List<User> result = this.getJdbcTemplate().query(GET_USER_BY_MOBILE,
                new Object[]{mobile}, mapper);
        if (CollectionUtils.isNotEmpty(result)) {
            return result.get(0);
        }
        return null;
    }

    private static final String GET_USER_BY_ID = "select * from y_user where id=?";

    @Override
    public User getUserByUserId(int userId) {
        List<User> result = this.getJdbcTemplate().query(GET_USER_BY_ID,
                new Object[]{userId}, mapper);
        if (CollectionUtils.isNotEmpty(result)) {
            return result.get(0);
        }
        return null;
    }


    private static final String MOBILE_EXIST = "select count(*) from y_user where mobile=?";

    @Override
    public boolean mobileExist(String mobile) {
        return 1 == this.getJdbcTemplate().queryForObject(MOBILE_EXIST,
                new Object[]{mobile}, Integer.class);
    }

    private static final String ADD_ADDRESS = "insert into y_user_address(user_id,mobile,address,name,lat,lng,city_code,area_code) values (?,?,?,?,?,?,?,?)";

    @Override
    public int addUserAddress(final UserAddressView userAddressView) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        this.getJdbcTemplate().update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con)
                    throws SQLException {
                PreparedStatement ps = con.prepareStatement(ADD_ADDRESS, Statement.RETURN_GENERATED_KEYS);
                ps.setInt(1, userAddressView.getUserId());
                ps.setString(2, userAddressView.getMobile());
                ps.setString(3, userAddressView.getAddress());
                ps.setString(4, userAddressView.getName());
                ps.setDouble(5, userAddressView.getLat());
                ps.setDouble(6, userAddressView.getLng());
                ps.setString(7, userAddressView.getCityCode());
                ps.setString(8, userAddressView.getAreaCode());
                return ps;
            }
        }, keyHolder);
        return keyHolder.getKey().intValue();
    }

    private static final String UPDATE_ADDRESS = "update y_user_address set mobile=?,address=?,name=?,lat=?,lng=?,city_code=?,area_code=? where id=?";

    @Override
    public boolean updateUserAddress(int id, String mobile, String address, String name, Double lat, Double lng, String cityCode, String areaCode) {
        return 1 == this.getJdbcTemplate().update(UPDATE_ADDRESS,
                new Object[]{mobile, address, name, lat, lng, cityCode, areaCode, id});
    }

    private static final String GET_USER_ADDRESS_BY_ID = "select * from y_user_address where id=?";

    @Override
    public UserAddressView getUserAddressById(int id) {
        List<UserAddressView> result = this.getJdbcTemplate().query(GET_USER_ADDRESS_BY_ID, new Object[]{id}, mapperAddress);
        if (CollectionUtils.isNotEmpty(result)) {
            return result.get(0);
        }
        return null;
    }

    private static final String GET_USER_ADDRESS_BY_USER_ID = "select * from y_user_address where user_id=? and status=0";

    @Override
    public List<UserAddressView> getUserAddressByUserId(int userId) {
        List<UserAddressView> result = this.getJdbcTemplate().query(GET_USER_ADDRESS_BY_USER_ID, new Object[]{userId}, mapperAddress);
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return result;
    }

    private static final String DEL_USER_ADDRESS_BY_ID = "update y_user_address set status=1 where id=?";

    @Override
    public boolean deleteUserAddressById(int id) {
        return 1 == this.getJdbcTemplate().update(DEL_USER_ADDRESS_BY_ID,
                new Object[]{id});
    }

    private static final String FEED_BACK = "insert into y_feedback(user_id,content) values (?,?)";

    @Override
    public boolean createFeedBack(int userId, String message) {
        return 1 == this.getJdbcTemplate().update(FEED_BACK,
                new Object[]{userId, message});
    }

}
